package fatworm.storage.types;

import java.nio.charset.*;

import fatworm.query.constant.*;
import fatworm.storage.table.*;

public class JString extends SType
{
    private String val;

    public JString()
    {
        this(null);
    }
    public JString(String val)
    {
        this.val = val;
    }
    @Override
    public void fromBytes(byte[] bytes)
    {
        switch (bytes[0])
        {
            case NULLFLAG :
                val = null;
                break;
            case NOTNULLFLAG :
                val = new String(bytes, 1, bytes.length - 1);
                break;
            default :
                throw new Error("!!!");
        }
    }
    @Override
    public byte[] toBytes()
    {
        byte[] res = new byte[length()];
        if (val == null)
        {
            res[0] = NULLFLAG;
        } else
        {
            res[0] = NOTNULLFLAG;
            byte[] bytes = val.getBytes();
            System.arraycopy(bytes, 0, res, 1, bytes.length);
        }
        return res;
    }
    @Override
    public int length()
    {
        if (val == null)
            return 1;
        return 1 + codingLen(val.length());
    }
    @Override
    public byte[] toBytesAsVID(VID vid)
    {
        throw new Error("!!!");
    }
    @Override
    public int lengthAsVID()
    {
        throw new Error("!!!");
    }
    @Override
    public int getType()
    {
        return Types.OTHER;
    }
    @Override
    public Constant toConstant()
    {
        if (val == null)
            return new NullConstant();
        else
            return new StringConstant(val);
    }
    @Override
    public void fromConstant(Constant c)
    {
        if (c instanceof NullConstant)
        {
            val = null;
        } else if (c instanceof StringConstant)
        {
            val = (String) c.asJavaVal();
        } else
            throw new Error("!!!");
    }
    private int codingLen(int strlen)
    {
        float bytesPerChar = Charset.defaultCharset().newEncoder().maxBytesPerChar();
        return strlen * (int) bytesPerChar;
    }
    @Override
    public SType newInstance()
    {
        throw new Error("!!!");
    }
    @Override
    public SVarChar copy()
    {
        throw new Error("!!!");
    }
}
